<template>
  <div class="publish-page">
   <el-card>
     <!-- 面包屑 -->
     <div slot="header">
       <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>{{$route.query.id?'修改':'发布'}}文章</el-breadcrumb-item>
        </el-breadcrumb>
     </div>
     <!-- form表单 -->
     <el-form ref="articleForm" label-width="120px" :model="articleForm" :rules="articleRules">
       <el-form-item label="标题 :" style="width:400px" prop="title">
         <el-input v-model="articleForm.title" placeholder="请输入文章标题"></el-input>
       </el-form-item>
       <el-form-item label="频道 :" prop="channel_id">
         <MyChannel :value="articleForm.channel_id" @input="articleForm.channel_id=$event">
         </MyChannel>
       </el-form-item>
       <el-form-item label="封面 :" prop="cover">
         <el-radio-group
         v-model="articleForm.cover.type"
         @change="changeCoverType">
           <el-radio :label="1">单图</el-radio>
           <el-radio :label="3">三图</el-radio>
           <el-radio :label="0">无图</el-radio>
           <el-radio :label="-1">自动</el-radio>
         </el-radio-group>
         <div v-if="articleForm.cover.type===1||articleForm.cover.type===3">
           <!-- name="image" 文件数据的字段名称 -->
            <!-- headers 配置请求头，类型对象 -->
           <el-upload
              :action="$http.defaults.baseURL+'v1_0/upload'"
              :file-list="articleForm.cover.images.map(item=>({url:item}))"
               name="image"
              :headers="{Authorization:`Bearer ${token}`}"
              :on-success="uploadSuccess"
              :on-remove="removeFile"
              list-type="picture-card"
              :limit="articleForm.cover.type"
              ref="upload"
              >
              <i class="el-icon-plus"></i>
            </el-upload>
         </div>
       </el-form-item>
       <el-form-item label="内容 :" prop="content">
         <!-- 富文本编辑器 -->
         <quillEditor
         v-model="articleForm.content"
         :options="editorOption"
         @blur="changeContent"
         ></quillEditor>
       </el-form-item>
        <el-form-item label="" v-if="$route.query.id">
         <el-button type="success" @click="update(false)">修改文章</el-button>
         <el-button @click="update(true)">存为草稿</el-button>
       </el-form-item>
       <el-form-item label="" v-else>
         <el-button type="success" @click="submit(false)">发布文章</el-button>
         <el-button @click="submit(true)">存为草稿</el-button>
       </el-form-item>
     </el-form>
   </el-card>
  </div>
</template>
<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'

import auth from '@/utils/auth'
export default {
  name: 'publish-page',
  components: {
    quillEditor
  },
  data () {
    // 定义上传图片规则
    const checkCover = (rule, value, callback) => {
      // value === this.articleForm.cover 封面对象
      // console.log(value)
      // 1. 单图 type === 1  校验 images 中有一张图片
      if (value.type === 1) {
        if (!value.images[0]) {
          callback(new Error('请上传一张图片'))
        }
      }
      // 2. 单图 type === 3  校验 images 中有三张图片
      if (value.type === 3) {
        if (!(value.images[0] && value.images[1] && value.images[2])) {
          callback(new Error('请上传三张图片'))
        }
      }
      // 校验成功后放行
      callback()
    }
    return {
      // 校验规则
      articleRules: {
        title: [{ required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 4, max: 50, message: '文章标题4-50字符', trigger: 'blur' }],
        channel_id: [{ required: true, message: '请选择文章频道', trigger: 'change' }],
        cover: [{ validator: checkCover, trigger: 'change' }],
        content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }]
      },
      // 表单对象
      articleForm: {
        title: null,
        content: null,
        channel_id: null,
        cover: {
          type: 1,
          images: []
        }
      },
      // token数据
      token: auth.getToken(),
      editorOption: {}
    }
  },
  created () {
    if (this.$route.query.id) {
      this.getArticle(this.$route.query.id)
    }
  },
  // 路由更新,路径地址不变,参数改变,当路由后边没有参数的时候,重置表单,有参数则填充表单
  beforeRouteUpdate (to, from, next) {
    if (to.query.id) {
      this.getArticle(to.query.id)
    } else {
      this.$refs.articleForm.resetFields()
    }
    next()
  },
  methods: {
    // 获取文章列表
    async getArticle (id) {
      const res = await this.$http.get('/v1_0/mp/articles/' + id)
      // console.log(res.data.data)
      this.articleForm = res.data.data
    },
    // 当封面按钮出现改变的时候,触发clearfiles事件,清空已上传的图片
    changeCoverType () {
      // 切换单图或三图的时候,数组重置
      this.articleForm.cover.images = []
      // 上传图片组件重置
      this.$refs.upload && this.$refs.upload.clearFiles()
      // 触发一次校验
      this.$refs.articleForm.validateField('cover')
    },
    // 上传图片成功
    uploadSuccess (res) {
      // res就是响应数据
      // console.log(res.data.data.url)
      this.articleForm.cover.images.push(res.data.url)
      // 上传三张图片后,再重新触发一次校验
      this.$refs.articleForm.validateField('cover')
    },
    // 校验内容是否为空
    changeContent () {
      this.$refs.articleForm.validateField('content')
    },
    // 删除文章功能
    removeFile (file) {
      console.log(file)
      // console.dir(file.response.data.url)
      // 根据找到删除图片的索引,根据索引删除
      const index = this.articleForm.cover.images.findIndex(item => item === file.url)
      // console.log(index)
      this.articleForm.cover.images.splice(index, 1)
      this.$refs.articleForm.validateField('cover')
    },
    // 发布文章功能
    submit (draft) {
      // 表单整体校验
      this.$refs.articleForm.validate(async valid => {
        // 如果表单整体校验后,发送发布文章请求
        if (valid) {
          try {
            await this.$http.post('/v1_0/mp/articles?draft=' + draft, this.articleForm)
            this.$message.success('发布成功!')
            this.$router.push('/article')
          } catch (e) {
            this.$message.error('发布失败')
          }
        }
      })
    },
    update (draft) {
      this.$refs.articleForm.validate(async valid => {
        // 如果表单整体校验后,发送发布文章请求
        if (valid) {
          try {
            // 修改到这里了!!!!
            await this.$http.put(`/v1_0/mp/articles/${this.$route.query.id}?draft=` + draft, this.articleForm)
            this.$message.success('修改成功!')
            this.$router.push('/article')
          } catch (e) {
            this.$message.error('修改失败')
          }
        }
      })
    }
  }
}

</script>
<style scoped lang="less">
::v-deep .el-upload-list__item{
  transition:none
}

::v-deep .ql-editor{
  height: 200px;
}
</style>
